package com.bds.btcdc.adapter.zb.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.adapter.service.ITradeService;
import com.bds.btcdc.api.model.*;
import com.bds.btcdc.model.UserKeys;
import com.bds.btcdc.adapter.zb.ZBAPIClient;
import com.bds.btcdc.service.UserKeysService;
import com.bds.btcdc.util.Const;
import com.bds.btcdc.util.EhcacheUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by DongChenchen on 2018/5/8 0008
 * zb交易api
 */
@Service
public class ZBTradeService implements ITradeService {
    private static final Logger logger = LoggerFactory.getLogger(ZBTradeService.class);
    private DecimalFormat df = new DecimalFormat(Const.END_WITH_COUNT);
    @Autowired
    private UserKeysService userKeysService;
    /**
         * 委托下单 request {"accesskey": your key, "amount": 0.01, "channel":
         * "ltcbtc_order", "event": "addChannel", "no": "14728151154382111746154",
         * "price": 100, "sign": 签名, "tradeType": 1 "acctType" : 1} response code :
         * 返回代码 message : 提示信息 id : 委托挂单号
         */
    @Override
    public Result makeOrder(Order order) {
        Result res=new Result();
        logger.info("ZB委托下单。。。。。。。。。。。。。。");
        UserKeys userKeys = getUserKeys(order.getUserId(), order.getExchange());
        String accessKey = userKeys.getAccess_key();
        String secretKey = userKeys.getSecret_key();
        if (!StringUtils.isEmpty(accessKey)&& !StringUtils.isEmpty(secretKey)) {
            ZBAPIClient client = ZBAPIClient.getInstance(order.getUserId(),accessKey, secretKey);
            String result=client.makeOrder(order);
            JSONObject json = JSONObject.parseObject(result);
            if(json.getInteger("code")==1000){
                String order_id=json.getString("id");
                OrderResponse response=new OrderResponse();
                    response.setStatus("ok");
                    response.setOrder_id(order_id);
                res.setResult(Const.SUC,response);
            }else{
                res.setResult(Const.FAIL,json.getString("message"));
            }
        }else{
            res.setResult(Const.FAIL,"access_key为空,或者secret_key为空！");
        }
        return res;

    }

    @Override
    public Result cancelOrder(long userId, String orderId) {
        return null;
    }

    @Override
    public Result getOrder(long userId, String orderId) {
        return null;
    }

    /**
     * 获取资产情况
     * @return
     *  //# Response
    {
        "result": {
            "coins": [
                {
                    "freez": "0.00000000",
                    "enName": "BTC",
                    "unitDecimal": 8,
                    "cnName": "BTC",
                    "unitTag": "฿",
                    "available": "0.00000000",
                    "key": "btc"
                },
                {
                    "freez": "0.00000000",
                    "enName": "LTC",
                    "unitDecimal": 8,
                    "cnName": "LTC",
                    "unitTag": "Ł",
                    "available": "0.00000000",
                    "key": "ltc"
                },
                ...
            ],
            "base": {
                "username": "134150***",
                "trade_password_enabled": true,
                "auth_google_enabled": false,
                "auth_mobile_enabled": true
            }
        }
    }
     */
    @Override
    public Result getAccount(UserKeys userKeys) {
        Result result=new Result();
        logger.info("获取zb资产情况。。。。。。。。。。。。。。");
        ZBAPIClient client = ZBAPIClient.getInstance(userKeys.getUser_id(),userKeys.getAccess_key(), userKeys.getSecret_key());
        String resu = client.getAccountInfo();
        if(!StringUtils.isEmpty(resu)) {
            try {
                JSONObject json = JSONObject.parseObject(resu);
                String resultStr = json.getString("result");
                JSONObject resultObj = JSONObject.parseObject(resultStr);
                JSONArray coins = resultObj.getJSONArray("coins");
                AccountInfo info = new AccountInfo();
                info.setUserId(userKeys.getUser_id());
                info.setExchange(Const.ZB.EXCHANGE);
                List<Asset> info_coins = new ArrayList<>();
                for (int i = 0; i < coins.size(); i++) {
                    JSONObject coinObj = coins.getJSONObject(i);
                    Asset coin = new Asset();
                    String currency=coinObj.getString("enName");
                    coin.setCurrency(currency.toUpperCase());
                    coin.setCount(df.format(coinObj.getBigDecimal("available")));
                    coin.setFreez_count(df.format(coinObj.getBigDecimal("freez")));
                    //只返回不为0 的币种
                    if(BigDecimal.ZERO.compareTo(coinObj.getBigDecimal("available"))!=0
                            ||BigDecimal.ZERO.compareTo(coinObj.getBigDecimal("freez"))!=0) {//过滤掉 为0的币种
                        //从缓存中取出 usdt币对的最新交易价格
                        String keys1=Const.ZB.EXCHANGE+"#"+currency.toUpperCase()+"_USDT";
                        String keys2=Const.ZB.EXCHANGE+"#"+"USDT_"+currency.toUpperCase();
                        String last_price = EhcacheUtils.getInstance().getCache(keys1);
                        String last_price2 = EhcacheUtils.getInstance().getCache(keys2);
                        if(StringUtils.isEmpty(last_price)){
                            if(!StringUtils.isEmpty(last_price2)){//反币对 不为空
                                last_price=BigDecimal.ONE.divide(new BigDecimal(last_price2),Const.BDM_SCALE,BigDecimal.ROUND_HALF_UP).toString();
                            }else {//api获取
                                BigDecimal lPrice = ZBAPIClient.getInstance().getLastPrice(currency.toLowerCase() + "_usdt");
                                if (lPrice == null) {
                                    //反币对
                                    BigDecimal price = ZBAPIClient.getInstance().getLastPrice("usdt_" + currency.toLowerCase());
                                    lPrice = BigDecimal.ONE.divide(price, Const.BDM_SCALE, BigDecimal.ROUND_HALF_UP);
                                }
                                last_price = lPrice.toString();
                            }
                        }
                        coin.setLast_price(df.format(Double.valueOf(last_price)));
                        //设置可用金额，冻结金额
                        BigDecimal amount=new BigDecimal(coin.getLast_price()).multiply(new BigDecimal(coin.getCount()));
                        coin.setAmount(df.format(amount));
                        BigDecimal freez=new BigDecimal(coin.getLast_price()).multiply(new BigDecimal(coin.getFreez_count()));
                        coin.setFreez(df.format(freez));
                        info_coins.add(coin);
                    }
                }
                info.setAssetList(info_coins);
                result.setResult(Const.SUC,info);
                return result;
            }catch (Exception e){
                e.printStackTrace();
                result.setResult(Const.FAIL,"从zb获取资产数据无效");
            }
        }else{
            result.setResult(Const.FAIL,"连接zb异常,未返回数据");
        }
        return result;
    }



    /**
     * 参数校验，都不能为空
     *
     * @return
     */
    private boolean volidate(Map<String, String> args) {
        for (Map.Entry<String, String> entry : args.entrySet()) {
            if (StringUtils.isEmpty(entry.getValue())) {
                return false;
            }
        }
        return true;
    }



    private UserKeys getUserKeys(Long userId, String exchange){
        //先从缓存中获取
        String cache = EhcacheUtils.getInstance().getCache(String.valueOf(userId));
        if(StringUtils.isEmpty(cache)){
            return userKeysService.getByUserIdAndExchange(userId, exchange);
        }else{
            String cache1 = EhcacheUtils.getInstance().getCache(String.valueOf(userId));
            List<UserKeys> userKeys = JSONObject.parseArray(cache1, UserKeys.class);
            for(UserKeys usr:userKeys){
                if(exchange.equals(usr.getExchange())){
                    return usr;
                }
            }
        }
        return null;
    }
}
